#pragma once

#include "Log.hpp"
#include "InetAddr.hpp"
#include <functional>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <strings.h>

using fun_t = std::function<std::string(const std::string&, const InetAddr&)>;

using namespace logModule;

const int defaultSockfd = -1;

class UdpServer
{
public:

    UdpServer(uint16_t port, fun_t task)
        :_port(port)
        ,_sockfd(defaultSockfd)
        ,_task(task)
        ,_isRunning(false)
    {
        ;
    }

    void init()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);           // 创建 socket
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket failure";
            exit(1);
        }
        LOG(LogLevel::DEBUG) << "socket success" << " sockfd:" << _sockfd;

        struct sockaddr_in local;
        bzero(&local, sizeof(local));

        local.sin_family = AF_INET;                         // 与 socket() 创建时指定的 domain 一致
        local.sin_port = htons(_port);                      // 端口号
        local.sin_addr.s_addr = INADDR_ANY;                 // 绑定所有可用接口

        int ret = bind(_sockfd, (struct sockaddr*)&local, sizeof(local));   // 将一个 socket 绑定到一个特定的 IP 地址和端口号上
        if (ret < 0)
        {
            LOG(LogLevel::FATAL) << "bind failure";
            exit(1);
        }
        LOG(LogLevel::DEBUG) << "bind success" << " sockfd:" << _sockfd;
    }

    void start()
    {
        _isRunning = true;
        while (true)
        {
            char buf[1024];

            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            
            ssize_t ret = recvfrom(_sockfd, buf, sizeof(buf) - 1, 0, (struct sockaddr*)&peer, &len);    // 接收数据，成功返回接收到的字节数
            if (ret > 0)
            {
                int peer_port = ntohs(peer.sin_port);               // 获取发送方的端口号
                std::string peer_ip = inet_ntoa(peer.sin_addr);     // 发送方 ip 网络字节序的二进制形式转换为点分十进制字符串

                buf[ret] = '\0';

                std::string result = _task(buf, peer);

                sendto(_sockfd, result.c_str(), result.size(), 0, (struct sockaddr*)&peer, len);        // 将处理的数据返回
            }
        }   
    }

    ~UdpServer()
    {
        ;
    }

private:

    int _sockfd;
    uint16_t _port;

    fun_t _task;
    bool _isRunning;
};
